using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Xeneize.SolaraBL;
using Xeneize.QBIntegration.Data;
using Xeneize.Utilities;

namespace WebDesktop.Pages.Sales
{
    public partial class SalesOrderEdit : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //Set current order
            if (Session["CurrentOrder"] == null)
            {
                Session.Add("CurrentOrder", Request.QueryString["cde"]);
            }
            else if (Request.QueryString["cde"] != null)
            {
                Session["CurrentOrder"] = Request.QueryString["cde"];
            }
            //This is used by the Comments grid.
            SetUserList();
            if (IsPostBack == false)
            {
                //Show Grid Comments
                SetCommentsDataSource(Session["CurrentOrder"].ToString());
                //Show Information
                ShowInformation();
            }

        }

        private void ShowInformation()
        {
            string OrderID = Session["CurrentOrder"].ToString();
            SalesOrder salesorder = new SalesOrder(OrderID);

            //Order Date
            this.lblSalesOrderDate.Text = salesorder.OrderDate;
            this.lblSalesOrderNumber.Text = OrderID;
            this.lblPONumber.Text = salesorder.PONumber;
            this.txtCustomer.Text = salesorder.Customer;
            this.txtJobAddress.Text = salesorder.JobAddress;            
            this.lblDaysInProduction.Text = salesorder.WeeksInProduction.ToString();
            this.lblSalesOrderClass.Text = salesorder.Class;
            this.txtProjectedShipDay.Text = salesorder.ProjectedShipDate;
            this.txtProductionShipDay.Text= salesorder.ProductionRcvedDate;
            this.lblSalesRep.Text = salesorder.SalesRep;
            
            Xeneize.SolaraBL.User solaraUser = new User(Membership.GetUser(User.Identity.Name).ProviderUserKey.ToString());
            //Users access privileges overwrite order's status access.
            this.txtProjectedShipDay.Enabled = solaraUser.HaveUpdateAccess("SalesOrders_Import", "ProjectedShipDate");
            this.txtProductionShipDay.Enabled = solaraUser.HaveUpdateAccess("SalesOrders_Import", "ProductionRcvDate");
            //Before linking the combo box with the order's status
            //we need to check to see if the user has access to that status.
            //If not we use a label instead of a combo box.
            try
            {
                string statusID = salesorder.StatusID.ToString();
                if (solaraUser.HaveAccessRightStatus(Convert.ToInt32(statusID)) == true)
                {
                    this.ddOrderStatus.SelectedValue = statusID;
                    this.ddOrderStatus.Visible = true;
                    this.lblOrderStatus.Visible = false;
                    this.ddOrderStatus.DataBind();
                }
                else
                {
                    //Show Order status as read only.
                    Status status = new Status(salesorder.StatusID);
                    this.ddOrderStatus.Visible = false;
                    this.lblOrderStatus.Text = status.Name;
                    this.lblOrderStatus.Visible = true;
                    //Disable Update button only the user does not have access to 
                    //modified either ProjectedShipDate or ProductionRcvDate
                    if (this.txtProjectedShipDay.Enabled == false && this.txtProductionShipDay.Enabled == false)
                    {
                        this.btn_OrderUpdate.Enabled = false;
                    }
                    status = null;
                }
            }
            catch (System.Exception ex)
            {
                SolaraExceptions.Save(ex);
            }
            finally
            {
                solaraUser = null;
            }
            
            //Get Items
            this.GridView1.DataSource = salesorder.GetItems(OrderID);
            this.GridView1.DataBind();
            salesorder = null;

            //Set Comments Tab as default
            this.CommentsGrid.Focus();

        }

        /// <summary>
        /// Sets the data source properties of the Comments Grid
        /// </summary>
        /// <param name="SalesOrderID"></param>
        private void SetCommentsDataSource(string SalesOrderID)
        {
            this.SqlDataSource1.SelectParameters.Clear();
            this.SqlDataSource1.SelectParameters.Add("SalesOrderID", SalesOrderID);
            this.CommentsGrid.DataBind();
         

        }
        protected void HyperLink1_DataBinding(object sender, EventArgs e)
        {
            if (User.IsInRole("Administrator") == false && !UserHasEditItemRights(((HyperLink)sender).ToolTip))
            {
                ((HyperLink)sender).NavigateUrl = "";
            }
            else
            {
                ((HyperLink)sender).NavigateUrl = String.Format("~/Pages/Sales/ItemEdit.aspx?cde={0}", ((HyperLink)sender).ToolTip);
            }

        }

        #region Comments Grid Region

        protected void CommentsGrid_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Insert" && Page.IsValid == true)
            {
                TextBox comment = (TextBox)this.CommentsGrid.FooterRow.FindControl("NewComment");                
                if (comment.Text.Length > 0 )
                {
                    string salesOrderID = Session["CurrentOrder"].ToString();
                    SalesOrderItemData orderData = new SalesOrderItemData();
                    orderData.SalesOrder_AddComments(salesOrderID, comment.Text, User.Identity.Name, false);
                    orderData = null;
                }
            }
            this.CommentsGrid.DataBind();
        }

        protected void CommentsGrid_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                DataRowView item = (DataRowView)e.Row.DataItem;
                //Set color red for comments that are Red Flag
                if (Convert.ToBoolean(item.Row.ItemArray[3]) == true)
                {
                    e.Row.BackColor = System.Drawing.Color.Red;
                    e.Row.ForeColor = System.Drawing.Color.White;

                }
                // Set color pink for comments that were Red Flag
                SalesOrder order = new SalesOrder();
                if (order.WasCommentRedFlag(Convert.ToInt32(item.Row.ItemArray[5])) == true)
                {
                    e.Row.BackColor = System.Drawing.Color.Pink;
                    e.Row.ForeColor = System.Drawing.Color.Black;

                }                
            }
        }

        #endregion


        #region Red Flag Tab
        private void SetUserList()
        {
            User user = new User();

            this.ddUserList.DataSource = user.GetUserList();
            this.ddUserList.DataTextField="Name";
            this.ddUserList.DataValueField = "Name";
            this.ddUserList.DataBind();
            user = null;
        }
        protected void btnSetRedFlag_Click(object sender, EventArgs e)
        {
            string salesOrderID = Session["CurrentOrder"].ToString();
            SalesOrderItemData orderData = new SalesOrderItemData();
            orderData.SalesOrder_AddComments(salesOrderID, txtRedFlagMessage.Text, User.Identity.Name, true,ddUserList.SelectedValue);
            orderData = null;
            this.CommentsGrid.DataBind(); //Refresh Grid
            this.GridView2.DataBind();
        }
        #endregion

        /// <summary>
        /// Check user's items rights
        /// </summary>
        /// <param name="ItemKey"></param>
        /// <returns></returns>
        private bool UserHasEditItemRights(string ItemKey)
        {
            bool bFlag = false;           
            
            //Get the current sales order holder (department)
            SalesOrderItem currentItem = new SalesOrderItem();
            Status status = new Status(currentItem.GetStatus(Convert.ToInt32(ItemKey)));            
            currentItem = null;            
            int ItemDepartmentId = status.DepartmentID;
            status = null;

            //Check the user department against the current order status
            User solaraUser = new User(Membership.GetUser(User.Identity.Name).ProviderUserKey.ToString());
            bFlag = solaraUser.HaveAccessRightDepartment(ItemDepartmentId);
            solaraUser = null;

            return bFlag;
        }
        protected void GridView2_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {            
            if (User.Identity.Name.ToLower() != ((GridView)sender).Rows[e.RowIndex].Cells[3].Text.ToLower())
            {
                e.Cancel = true;
            }
        }

        protected void GridView2_RowDeleted(object sender, GridViewDeletedEventArgs e)
        {
            this.CommentsGrid.DataBind(); //Refresh Comments grid           
        }

        protected void btn_OrderUpdate_Click(object sender, EventArgs e)
        {
            //Before we can update we need to check the user's access.
            //If the user does not have access to the status of this order, 
            //we need to collect the statusid from the status name.
            //We know that by looking at the enable property of the status combobox.
            //if the enable property is false we know we need to use the name of the status 
            //to collect the statusid.
            Status oStatus = null;
            int statusId = 0;
            if (this.ddOrderStatus.Visible == false)
            {
                //Get the statusId from the Status name
                oStatus = new Status(this.lblOrderStatus.Text);
            }
            else
            {
                oStatus = new Status(Convert.ToInt32(this.ddOrderStatus.SelectedValue));
            }
            //Get location from status            
            int locationId = oStatus.LocationID;
            
            Transfers trxn = new Transfers();

            statusId = trxn.GetTargetStatus(locationId, oStatus.ID);
            trxn = null;

            //Standarize ProjectedProductionDay
            //we need to do this, because Alberto wants to see a blank box
            //when the production date has not been set, 1/1/1900 is our default day.
            DateTime ProductionShipDay = new DateTime(1900,1,1);
            if  ( this.txtProductionShipDay.Text.Length >0) 
                ProductionShipDay = Convert.ToDateTime(this.txtProductionShipDay.Text);

            if (this.txtProjectedShipDay.Text.Length == 0)
                this.txtProjectedShipDay.Text = new DateTime(1900, 1, 1).ToString();

            SalesOrder order = new SalesOrder(this.lblSalesOrderNumber.Text);
            order.Update(Convert.ToInt32(statusId),
                         Convert.ToDateTime(this.txtProjectedShipDay.Text),
                         ProductionShipDay,
                         this.lblSalesOrderNumber.Text, 
                         Convert.ToInt32(this.ddOrderStatus.SelectedValue),
                         this.lblSalesOrderNumber.Text);

            //Insert Entry in StatusTransactionLog
            order.InsertLogEntry(this.lblSalesOrderNumber.Text,
                                  oStatus.Name,
                                  User.Identity.Name);

            //Check if the Status selected is a StopMark status. In case it is we need to
            //mark today as the stop counting date.
            if (oStatus.GetStopMark() == true)
            {
                //Update SalesOrder StopDaysCount if StopDateCount is not set
                if (order.StopCountDate =="1/1/1900")
                {
                    order.SetStopDay();
                }
            }

            //Check if the Order Status is a special status, and the order items need to 
            //be updated.   
            int itemStatus = 0;
            if ( (itemStatus = oStatus.StatusCycle_GetItemStatus(statusId)) != 0)
            {
                order.StatusCycles_UpdateOrderItems(this.lblSalesOrderNumber.Text,itemStatus);
                //Aca tengo que llamar a una nueva function que 
                //acepte un order id y un status para cambiar 
                //el status de todos los items.
            }
            order = null;
            oStatus = null;
            //Refresh information
            ShowInformation();
        }

        protected void StatusDataSource_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
        {
            User objUser = new User(Membership.GetUser(User.Identity.Name).ProviderUserKey.ToString());
            e.ObjectInstance = objUser;
            objUser = null;
        }

        protected void txtProductionShipDay_TextChanged(object sender, EventArgs e)
        {
            
        }

        protected void RadComboBox1_ItemsRequested(object o, Telerik.WebControls.RadComboBoxItemsRequestedEventArgs e)
        {
            RadComboBox1.Items.Add(new Telerik.WebControls.RadComboBoxItem("One", "1"));
            RadComboBox1.Items.Add(new Telerik.WebControls.RadComboBoxItem("One", "2"));
            RadComboBox1.Items.Add(new Telerik.WebControls.RadComboBoxItem("One", "3"));
        }


    }
}
